<?php

App::uses("String", "Utility");    
App::uses("GenericUtil", "Lib");    
App::uses('AttachUtil', 'Lib');

class UploadController extends AppController {
    // var $helpers = array ('Html','Form');
    var $name = 'Upload'; // riferimento alla cartella delle view

    // questa riga permette di utilizzare il componente Permission
    var $components = array('Permission','Thumb');
        
    public function beforeFilter(){
		if(!$this->request->is('ajax'))
			parent::beforeFilter();
        // don't require logging in for login and logout actions
        $this->Auth->allow('ajaxupload','upload','save','delete');
    	Controller::loadModel('Attach');
    }

    public function index($attachTipo="FOTO") {
		// $this->layout="ajax";
		// $this->autorender = false;
    	// App::uses("UploadHandler", "Lib/jqueryupload");
		// $upload_handler = new UploadHandler();
		// die;
		
		$this->set("attachTipo",$attachTipo);
		$attaches = $this->Attach->find("all",array("conditions" => array("Attach.attach_tipo" => $attachTipo)));
		$this->set("attaches",$attaches);
		
    }

	protected function save($file, $vars=null) {
		try {
			$fileUploaded = array();
    	    $isMobile = $this->request->is('mobile');
    		$this->Attach->create();
			// pr($this->request->data["attachTipo"]);die;
    		AttachUtil::upload($this->Attach, $file, $this->request->data["attachTipo"],$this->Session->read("Auth.User.id"));
			if ($this->Attach->attachTipo->field("thumb")) {
				try {
					$this->Thumb->generateThumb($this->Attach->getAbsolutePath(), $this->Attach->filename, $this->Attach->field("tipo"),$isMobile);
		    	} catch (Exception $e) {
					$this->Attach->delete();
					throw $e;
		    	}
			}
	        $fileUploaded['id']=$this->Attach->id;
	        $fileUploaded['webpath']=$this->Attach->getWebFile();
	        $fileUploaded['thumb_webpath']=$this->Attach->getThumbFile();
			return $fileUploaded;
        } catch (Exception $e) {
	    	CakeLog::error($e->getMessage());
            throw $e;
        }
    }

	public function upload($vars=null) {
    	$ds = null;
		try {
		    $ds = $this->Attach->getDataSource();
            $isMobile = $this->request->is('mobile');
            $filesuploaded = array();
            $errorMessage = null;
            foreach ($_FILES as $files) {
        		foreach (GenericUtil::reArrayFiles($files) as $file) {
	            	try {
						$ds->begin();
						array_push($filesuploaded,$this->save($file,func_get_args()));
						$ds->commit();
	            	} catch (Exception $e2) {
				    	if (isset($ds))
				    		$ds->rollback();
						$errorMessage.="<br>".$e2->getMessage();
	            	}
				}
            }
			// pr($errorMessage);die;
			$this->Session->setFlash(__("Upload completato."),"default");
			if ($errorMessage)
				$this->Session->setFlash($errorMessage,"default",null,"error");
        } catch (Exception $e) {
	    	if (isset($ds))
	    		$ds->rollback();
	    	CakeLog::error($e->getMessage());
			$this->Session->setFlash(__("Errore: "). $e->getMessage(),"default",null,"error");
        }
		$this->redirect($this->referer());
    }

    public function ajaxupload() {
        // per tutte le chiamate imposto l'ajax layout
        $this->layout="ajax";
        $this->autorender = false;
		// if($this->request->is('ajax')) {
		if(true) {
	    	$ds = null;
			try {
			    $ds = $this->Attach->getDataSource();
				// $ds->useNestedTransactions = true;
				$data=array();
	            $filesuploaded = array();
	            foreach ($_FILES as $file) {
					$ds->begin();
		            array_push($filesuploaded,$this->save($file,func_get_args()));
					$ds->commit();
				}
				$data["success"] = true;
	            $data["message"] = __("Numero file salvati: ") . count($filesuploaded);
	            $data["fileuploaded"] = $filesuploaded;
				echo json_encode($data);
	            die();
			} catch (exception $e) {
		    	if (isset($ds))
		    		$ds->rollback();
		    	CakeLog::error($e->getMessage());
				$data = array('success'=> false,'message'=>$e->getMessage(),'level'=>'error','fileuploaded' => $filesuploaded);
				echo json_encode($data);
	            die();
			} 
		} else {
			throw new MethodNotAllowedException();
		}
    }
    
    protected function remove() {
        
    }

	public function delete() {
	    $vars = func_get_args();
        $id = $vars[0];
        $this->loadModel("Attach");
	    $ds = $this->Attach->getDataSource();
		$ds->begin();
		try {
            $this->remove($vars);
			$this->Attach->recursive = 0;
			$attach = $this->Attach->read(null,$id);
			if ($this->Attach->delete()) {
		        if ($this->Attach->attachTipo->field("thumb")) {
		            try {
		                $this->Thumb->deleteThumb($this->Attach->getAbsolutePath(), $this->Attach->filename);
		            } catch (exception $e) {
				    	CakeLog::error($e->getMessage());
		                throw $e;
		            }
		        }
			} else
				throw new Exception(__("Attach non cancellato."));
			$ds->commit();
			if($this->request->is('ajax')) {
				$this->layout="ajax";
				$this->autorender = false;
				$data=array();
				$data["success"] = true;
	            $data["message"] = __("Attach cancellato.");
				echo json_encode($data);
	            die();
			} else {
				$this->layout="default";
				$this->Session->setFlash(__("Attach cancellato."));
				$this->redirect($this->referer());
			}
		} catch (Exception $e) {
			CakeLog::error($e->getMessage());
	    	if (isset($ds))
	    		$ds->rollback();
			if($this->request->is('ajax')) {
				$this->layout="ajax";
				$this->autorender = false;
				$data = array('success'=> false,'message'=>$e->getMessage(),'level'=>'error');
				echo json_encode($data);
	            die();
			} else {
				$this->layout="default";
				$this->Session->setFlash($e->getMessage(),"default",null,"error");
				$this->redirect($this->referer());
			}
		}
	}

}
?>